package com.binhanh.controller.uploads;

import java.util.ArrayList;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.binhanh.common.Utils;
import com.binhanh.common.constant.FileType;
import com.binhanh.model.YoutubeVideo;
import com.binhanh.service.ServiceUtils;
import com.binhanh.sql.bo.Video;
import com.binhanh.sql.dao.VideoDAO;

public class YouTubeHandler {

	public static final String YOUTUBE_KEY = "AIzaSyAQqfkeDBqSN-iZMZRAsQglYTnzJho0DFk";

	private String mFilePath;

	public YouTubeHandler(String filePath) {
		super();
		this.mFilePath = filePath;
	}

	public void getYoutubeInfo() {
		ArrayList<Video> lst = ExcelHandler.readVideoExcel(mFilePath);
		for (final Video video : lst) {
			final String url = createYoutubeUrl(video.youtubeId);
			if (url == null)
				continue;
			new Thread(new Runnable() {

				@Override
				public void run() {
					try {
						String data = ServiceUtils.getServiceByGet(url);
						updateYoutubeInfo(video, data);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}).start();
		}
	}

	public void updateYoutubeInfo(final Video video, String data) {
		
		System.out.println(data + "\n");
		
		try {
			JSONObject js = new JSONObject(data);
			JSONArray jsonArray = js.getJSONArray("items");
			if (jsonArray.length() > 0) {
				JSONObject items = jsonArray.getJSONObject(0);
				
				//lấy snippet
				JSONObject snippet = items.getJSONObject("snippet");
				
				//thời gian cập nhật
				String publishedAt = snippet.getString("publishedAt");
				video.setCreateDate(Utils.convertStringToDate(publishedAt.substring(0, 9)));
				video.setUpdateDate(new Date());
				
				//tiêu đề mặc địch video
				video.setDefaultTitle(snippet.getString("title"));
				
				//Miêu tả ngắn
				video.setDescription(snippet.getString("description"));
				
				
				JSONObject thumbnails = snippet.getJSONObject("thumbnails");
				video.setDefaultThumb(getThumbnailsUrl(thumbnails,"default"));
				video.setMediumThumb(getThumbnailsUrl(thumbnails,"medium"));
				video.setHighThumb(getThumbnailsUrl(thumbnails,"high"));
				video.setStandardThumb(getThumbnailsUrl(thumbnails,"standard")); 
				video.setMaxresThumb(getThumbnailsUrl(thumbnails,"maxres"));
				
				
				//lấy thống kê
				JSONObject statistics = items.getJSONObject("statistics");
				video.setViewCount(statistics.getInt("viewCount"));
				video.setLikeCount(statistics.getInt("likeCount"));
				video.setDislikeCount(statistics.getInt("dislikeCount"));
				video.setFavoriteCount(statistics.getInt("favoriteCount"));
				video.setCommentCount(statistics.getInt("commentCount"));
				
				//loại file để xem
				video.setFileType(FileType.ONLINE.getId());
				
				ArrayList<Video> lst = new ArrayList<Video>();
				lst.add(video);
				new VideoDAO().insert(lst);
				
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

	}
	
	private static String getThumbnailsUrl(JSONObject thumbnails, String key){
		String ret = "";
		JSONObject item = null;
		try {
			
			item = thumbnails.getJSONObject(key);
			
		} catch (JSONException e) {
//			e.printStackTrace();
		}
		
		if(item != null){
			ret = item.getString("url");
		}
		return ret;
				
	}

	/**
	 * Tạo link để lấy thông tin từ youtube
	 * 
	 * @param youtubeId
	 * @return
	 */
	private static String createYoutubeUrl(String youtubeId) {
		if (youtubeId == null || youtubeId.length() == 0)
			return null;
		String url = "https://www.googleapis.com/youtube/v3/videos?id="
				+ youtubeId
				+ "&key="
				+ YOUTUBE_KEY
				+ "&part=snippet,statistics&fields=items(snippet(publishedAt,title,description,thumbnails),statistics)";
		return url;
	}

}
